<template>
  <view class="container">
    <cu-custom bgColor="bg-blue" :isBack="true" style="width: 100%;">
      <block slot="backText">返回</block>
      <block slot="content">打卡</block>
    </cu-custom>
    <!-- 顶部时间显示 -->
    <view class="time-section">
      <text class="current-time">{{ currentTime }}</text>
      <text class="current-date">{{ currentDate }}</text>
    </view>

    <!-- 打卡主按钮 -->
    <view class="punch-main">
      <view class="punch-btn" @click="handlePunch">
        <view class="btn-circle">
          <text class="btn-text">点击打卡</text>
        </view>
      </view>
      <text v-if="false" class="location-text">
        <uni-icons type="location-filled" size="16" color="#666"></uni-icons>
        {{ locationAddress || '正在获取位置...' }}
      </text>
    </view>

    <!-- 悬浮扫码打卡按钮 -->
    <view class="floating-scan-btn" @click="handleScan">
      <uni-icons type="scan" size="24" color="#1890FF"></uni-icons>
    </view>

    <view class="scan-section" @click="attendanceDetail">
      <uni-icons type="paperplane" size="22" color="#1890FF"></uni-icons>
      <text class="scan-text">查看打卡记录</text>
    </view>

    <!-- 打卡记录 -->
    <view class="record-section">
      <view class="section-title">今日打卡记录</view>
      <view v-for="(item, index) in punchRecords" :key="index" class="record-item">
        <view class="record-left">
          <text class="record-type">{{ item.type }}</text>
          <text class="record-time">{{ item.time }}</text>
        </view>
        <text :class="['record-status', item.status]">{{ item.statusText }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/common/request.js';
export default {
  data() {
    return {
      currentTime: '00:00',
      currentDate: '2023年1月1日 星期一',
      locationAddress: '',
      punchRecords: [
        // { type: '张三', time: '09:00', status: 'success', statusText: '正常' },
        // { type: '张三', time: '09:00', status: 'waiting', statusText: '正常' }
      ]
    }
  },
  computed: {
    // punchButtonText() {
    //   return this.punchRecords[1].time === '--:--' ? '上班打卡' : '下班打卡'
    // }
  },
  mounted() {
    this.updateTime()
    this.getAttendanceTodayData()
    setInterval(this.updateTime, 1000)
    //this.getLocation()
  },
  methods: {
    attendanceDetail() {
      uni.navigateTo({
        url: '/pages-others/attendance/attendanceDetail'
      })
    },
    getAttendanceTodayData() {
      let opts = {
        url: 'api/getAttendance',
        method: 'get'
      };

      // 获取当前日期（格式：yyyy-MM-dd）
      const date = this.getCurrentDate();

      let savingRequestData = {
        date: date,
      };

      request.httpTokenRequest(opts, savingRequestData).then(res => {
        if (res.data.code == 1) {
          // 清空原有数据
          this.punchRecords = [];

          if (res.data.data.length > 0) {
            // 格式化接口数据
            res.data.data.forEach(item => {
              // 转换时间格式（23:20:38 -> 23:20）
              const time = item.AddTime.split(' ')[1].substr(0, 5);

              // 构建打卡记录对象
              const record = {
                type: item.QrcodeName,     // 设备名称
                time: time,                // 打卡时间
                userId: item.SignUserId,   // 用户ID
                status: item.isdel === 0 ? 'success' : 'expired', // 状态判断
                statusText: item.isdel === 0 ? '有效打卡' : '已失效'
              };

              this.punchRecords.push(record);
            });

            // 如果需要显示用户名（假设有用户名字段）
            // record.type = item.QrcodeUserName || '未知用户';

            // 按时间排序（如果需要）
            this.punchRecords.sort((a, b) => a.time.localeCompare(b.time));

          } else {
            uni.showToast({
              title: '今日暂无打卡记录',
              icon: 'none',
              duration: 2000
            });
          }

          // 更新页面数据
          this.$forceUpdate();

        } else {
          uni.showToast({
            title: res.data.msg || '数据加载失败',
            icon: 'none',
            duration: 3000
          });
        }
      }).catch(err => {
        console.error('请求异常:', err);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 3000
        });
      });
    },
    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
      const day = String(date.getDate()).padStart(2, '0');        // 日期补零
      return `${year}-${month}-${day}`;
    },
    updateTime() {
      const date = new Date()
      this.currentTime = date.toLocaleTimeString('zh-CN', { hour12: false }).slice(0, 5)
      this.currentDate = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
    },
    // async getLocation() {
    //   try {
    //     const res = await uni.getLocation({ type: 'gcj02' })
    //     // 调用逆地理编码接口（需要自行实现或使用地图服务商API）
    //     this.locationAddress = await this.reverseGeocoder(res.latitude, res.longitude)
    //   } catch (error) {
    //     console.error('获取位置失败', error)
    //   }
    // },
    async reverseGeocoder(lat, lng) {
      // 示例：使用腾讯地图逆地理编码
      const KEY = 'YOUR_MAP_KEY'
      const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${KEY}`
      const res = await uni.request({ url })
      return res.data.result.address
    },
    handlePunch() {
		//
		let that=this
		let opts = {
		  url: 'api/goAttendance',
		  method: 'get'
		};
		let savingRequestData = {
		  latitude: '',
		  longitude: '',
		  qrcodeId: ''
		}
		uni.getLocation({
		  type: 'gcj02',
		  isHighAccuracy: true,
		  success(res3) {
		    savingRequestData.latitude = res3.latitude;
		    savingRequestData.longitude = res3.longitude;
		    request.httpTokenRequest(opts, savingRequestData).then(res => {
		      if (res.data.code == 1) {
		        uni.showToast({
		          title: '打卡成功',
		          icon: 'none',
		          duration: 3000
		        });
		        that.getAttendanceTodayData()
		      }
		      else {
		        uni.showToast({
		          title: res.data.msg,
		          icon: 'none',
		          duration: 3000
		        });
		      }
		    });
		  },
		  fail: function () {
		    uni.hideLoading();
		    uni.showToast({
		      title: '定位失败，请退出登陆重新开启定位',
		      icon: 'none',
		      duration: 4000
		    });
		  }
		});
    },
    handleScan() {
      let that = this
      uni.scanCode({
        onlyFromCamera: true,
        success: function (res) {
          that.result2 = res.result;
          let qrcodeId = request.getRequest(res.result, 'id')

          let opts = {
            url: 'api/goAttendance',
            method: 'get'
          };
          let savingRequestData = {
            latitude: '',
            longitude: '',
            qrcodeId: ''
          }
          savingRequestData.qrcodeId = qrcodeId;
          uni.getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
            success(res3) {
              savingRequestData.latitude = res3.latitude;
              savingRequestData.longitude = res3.longitude;
              request.httpTokenRequest(opts, savingRequestData).then(res => {
                if (res.data.code == 1) {
                  uni.showToast({
                    title: '打卡成功',
                    icon: 'none',
                    duration: 3000
                  });
                  that.getAttendanceTodayData()
                }
                else {
                  uni.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 3000
                  });
                }
              });
            },
            fail: function () {
              uni.hideLoading();
              uni.showToast({
                title: '定位失败，请退出登陆重新开启定位',
                icon: 'none',
                duration: 4000
              });
            }
          });
        },
        fail(scanFailErr) {
          uni.hideLoading();
          console.log(scanFailErr)
        }
      });
    }
  }
}
</script>

<style lang="scss">
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

.time-section {
  text-align: center;
  padding: 40rpx 0;
  .current-time {
    display: block;
    font-size: 64rpx;
    color: #333;
    font-weight: bold;
  }
  .current-date {
    font-size: 28rpx;
    color: #666;
  }
}

.punch-main {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx 0;
  margin: 20rpx;
  .punch-btn {
    display: flex;
    justify-content: center;
    .btn-circle {
      width: 300rpx;
      height: 300rpx;
      border-radius: 50%;
      background: linear-gradient(to right, #1890FF, #0066FF);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #fff;
      .btn-text {
        font-size: 40rpx;
        font-weight: bold;
      }
    }
  }
  .location-text {
    display: block;
    text-align: center;
    font-size: 24rpx;
    color: #666;
    margin-top: 20rpx;
  }
}

.scan-section {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  margin: 20rpx;
  padding: 30rpx 0;
  border-radius: 12rpx;
  .scan-text {
    margin-left: 10rpx;
    color: #1890FF;
    font-size: 28rpx;
  }
}

.record-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 20rpx;
  .section-title {
    font-size: 28rpx;
    color: #333;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #eee;
  }
  .record-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1px solid #efefef;
    .record-left {
      .record-type {
        display: block;
        font-size: 28rpx;
        color: #333;
      }
      .record-time {
        font-size: 24rpx;
        color: #666;
      }
    }
    .record-status {
      font-size: 26rpx;
      &.success {
        color: #52c41a;
      }
      &.warning {
        color: #faad14;
      }
      &.error {
        color: #ff4d4f;
      }
    }
  }
}

.floating-scan-btn {
  position: fixed;
  right: 60rpx;
  bottom: 120rpx;
  width: 120rpx;
  height: 120rpx;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}
</style>